package com.flaskpy.web.eternity.log.service.impl;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import cn.hutool.json.JSONUtil;
import com.flaskpy.web.eternity.log.entity.LogArgs;
import com.flaskpy.web.eternity.log.entity.LogInfo;
import com.flaskpy.web.eternity.log.service.IAopLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Slf4j
public class AopLogService implements IAopLogService {

    @Resource(name = "aopLogThreadPoll")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Override
    public void save(LogArgs logInfo) throws InterruptedException {

        this.threadPoolTaskExecutor.execute(()->{
            this.outputLogInfo(logInfo);
        });
    }
    protected void outputLogInfo(LogArgs logInfo){
        JoinPoint joinPoint = logInfo.getJoinPoint();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        LogInfo logDetail=new LogInfo();
        logDetail.setAopMethodName( joinPoint.getTarget().getClass().getName() + "." + signature.getName() + "()");
        logDetail.setAopArgs(Arrays.asList(joinPoint.getArgs()));
        logDetail.setHttpMethod(logInfo.getRequest().getMethod());
        logDetail.setHttpUri(logInfo.getRequest().getRequestURI());
        logDetail.setElapsed(logInfo.getElapsed());
        logDetail.setLevel(logInfo.getLevel());
        logDetail.setResult(logInfo.getResult());
        logDetail.setStartTime(logInfo.getStartTime());
        logDetail.setTitle(logInfo.getTitle());
        UserAgent ua = UserAgentUtil.parse(logInfo.getRequest().getHeader("User-Agent"));
        logDetail.setIsMobile(ua.isMobile());
        logDetail.setUserAgent(logInfo.getRequest().getHeader("User-Agent"));
        logDetail.setIp(getIp(logInfo.getRequest()));
        String json = JSONUtil.toJsonStr(logDetail);
        log.info(json);
    }
    /**
     * 获取ip地址(ctrlC模式)
     */
    private static final String UNKNOWN = "unknown";
    private static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String comma = ",";
        String localhost = "127.0.0.1";
        if (ip!=null && ip.contains(comma)) {
            ip = ip.split(",")[0];
        }
//        if (localhost.equals(ip)) {
//            // 获取本机真正的ip地址
//            try {
//                ip = InetAddress.getLocalHost().getHostAddress();
//            } catch (UnknownHostException e) {
//                log.error(e.getMessage(), e);
//            }
//        }
        return ip;
    }
}
